package handler

import (
	"github.com/gin-gonic/gin"

	"github.com/lab-online/pkg/auth"
	mw "github.com/lab-online/pkg/middleware"
	"github.com/lab-online/pkg/resp"

	"github.com/lab-online/internal/user/constant"
	"github.com/lab-online/internal/user/entity"
)

type RegisterReqBody struct {
	Username string `json:"username" binding:"required,len=8" example:"20240126"`        // 学号或者工号
	Name     string `json:"name" binding:"required,max=16" example:"杏鸣"`                 // 姓名
	Password string `json:"password" binding:"required,max=64,min=8" example:"12345678"` // 密码
	Role     uint8  `json:"role" binding:"required,min=1,max=7" example:"7"`             // 权限
}

var RegisterValidator = mw.NewValidator(func() *mw.ValidatorOptions {
	return &mw.ValidatorOptions{
		Body: &RegisterReqBody{},
	}
})

// Register
//
//	@Summary				注册
//	@Description			## 权限说明
//	@Description			`1` 学生 `2` 为教师 `4` 管理员
//	@Description			使用位运算叠加权限,如 `1|2|4=7` ,即为管理员+教师+学生, 只能创建比自己权限低的用户
//	@Description.markdown	Register
//	@Tags					user
//	@Accept					json
//	@Produce				json
//	@Security				bearer
//	@Param					Authorization	header		string			true	"`Teacher` | `Admin`"
//	@Param					Body			body		RegisterReqBody	true	"JSON 请求体"
//	@Success				201				{object}	resp.BaseRespBody
//	@Failure				400				{object}	resp.FailedRespBodyString
//	@x-apifox-status		"testing"
//	@Router					/v1/users/ [post]
func (h *Handler) Register(c *gin.Context) {
	authEntity := c.MustGet(auth.KeyAuth).(auth.AuthEntity)
	user := c.MustGet(mw.KeyBody).(*RegisterReqBody)

	userEntity := entity.NewUserEntity(
		entity.WithPassword(user.Password),
		entity.WithUsername(user.Username),
		entity.WithName(user.Name),
		entity.WithRole(user.Role),
	)

	if _, err := h.domain.AddUser(userEntity, authEntity); err != nil {
		resp.ErrorHandler(c, err)
		return
	}

	resp.Created[any](c, constant.CodeSuccessRegister)
}
